package com.xinkao.example.config.shiro;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xinkao.example.dao.LoginDao;
import com.xinkao.example.service.LoginService;
import com.xinkao.example.util.RandomUtils;
import com.xinkao.example.util.RedisUtils;
import com.xinkao.example.util.constants.Constants;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: LXF
 * @description: 自定义Realm
 * @date: 2017/10/24 10:06
 */
public class UserRealm extends AuthorizingRealm {

	@Resource
	private RedisUtils redisUtils;
	@Resource
	private LoginService loginService;
	@Resource
	private LoginDao loginDao;

	@Override
	@SuppressWarnings("unchecked")
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		JSONObject json = redisUtils.get(principals.getPrimaryPrincipal().toString(), JSONObject.class);
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		if (json != null && json.getJSONArray("userPermission") != null) {
			//为当前用户设置角色和权限
			List<String> userPermission = JSON.parseArray(json.getJSONArray("userPermission").toJSONString(), String.class);
			authorizationInfo.addStringPermissions(userPermission);
		}
		return authorizationInfo;
	}

	/**
	 * 验证当前登录的Subject
	 * LoginController.login()方法中执行Subject.login()时 执行此方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		String loginName = (String)authcToken.getPrincipal();
		String password = new String((char[]) authcToken.getCredentials());
		// 校验用户信息，错误时返回异常信息
		JSONObject user =  loginService.getUser(loginName, password);
		if (user == null) {
			throw new AuthenticationException();
		}
		//将权限放在redis中
		List<String> userPermission = new ArrayList<>();
		if ("1".equals(user.getString("isSuper"))) {
			userPermission = loginDao.getAllPermission();
		} else {
			userPermission = loginDao.getUserPermission(user.getString("userId"));
		}
		user.put("userPermission", userPermission);

		//用户和权限 保存到redis, 有效期为8小时
		String token = RandomUtils.getUUID();
		redisUtils.set(token, user, 60*60*8);
		//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				token,
				password,
				getName()
		);
		return authenticationInfo;
	}

	/**
	 * 为超级管理员添加所有权限
	 * @param principals
	 * @param permission
	 * @return
	 */
//	@Override
//	public  boolean isPermitted(PrincipalCollection principals, String permission){
//		String userName = principals.getPrimaryPrincipal().toString();
//		JSONObject user = userDao.getUserByName(userName);
//		String isSuper = "0";
//		if(null != user){
//			isSuper = user.getString("isSuper");
//		}
//		return adminAccount.equals(isSuper) || super.isPermitted(principals,permission);
//	}

	/**
	 * 为超级管理员添加所有角色
	 * @param principals
	 * @param roleIdentifier
	 * @return
	 */
//	@Override
//	public boolean hasRole(PrincipalCollection principals, String roleIdentifier) {
//		String userName = principals.getPrimaryPrincipal().toString();
//
//		JSONObject user = userDao.getUserByName(userName);
//		String isSuper = "0";
//		if(null != user){
//			isSuper = user.getString("isSuper");
//		}
//		return adminAccount.equals(isSuper) ||super.hasRole(principals,roleIdentifier);
//	}
}
